<template>
    <div>
        <Table highlight-row ref='table' :columns='columns' :loading='loading' :data='callData' :height="520">
            <!-- <template slot-scope="{row}" slot="info">
            </template> -->
            <template slot-scope="{ row }" slot="callState">
                <Badge v-if="row.is_call_str === '未接听'" status="warning" text="未接听" ></Badge>
                <Badge v-if="row.is_call_str === '已接听'" status="success" text="已接听" ></Badge>
            </template>
            <template slot-scope="{row}" slot="option">
                <a @click="handleContactClue(row)">详细</a>
            </template>
        </Table>
        <Page
            show-total
            show-elevator
            show-sizer
            :total="total"
            :current.sync="params.page"
            :page-size="params.pageSize"
            :page-size-opts="pageOpts"
            @on-change="changepage"
            @on-page-size-change="changepageSize"
            class="ivu-mt-16"
        ></Page>
        <!-- <div class='ivu-mt ivu-text-center'>
            <Page show-total show-elevator show-sizer :total='total' :current.sync='params.page'
                  :page-size='params.pageSize' :page-size-opts='pageOpts' @on-change='changepage'
                  @on-page-size-change='changepageSize' />
        </div> -->
        <Modal ref="contact" title="联系线索客户" v-model="contactClue" :mask-closable="false" width="1000"
               @on-cancel="handleDrawerCancel('formItem')">
            <DescriptionList :col="3" v-if="createData">
                <Description term="手机号：">{{createData.mobile}}</Description>
                <Description term="性别：">{{createData.gender}}</Description>
                <Description term="年龄：">{{createData.age}}</Description>
                <Description term="微信号：">{{createData.wechat_id}}<Tag class="ivu-ml-8" v-if="createData.is_add" color="success">已添加</Tag></Description>
                <Description term="部位：">{{createData.parts_name}}</Description>
                <Description term="城市：">{{createData.city_name}}</Description>
                <Description term="客服备注：">{{createData.customer_remark}}</Description>
                <!-- <Description term="来电号码：">{{ createData.called_tel }}</Description>
                <Description term="来电时间：">{{ createData.call_time }}</Description>
                <Description term="来电状态：">{{ createData.is_call_str }}</Description>
                <Description term="通话时长：">{{ createData.duration_str }}</Description> -->
            </DescriptionList>
            <Divider></Divider>
            <Form label-position="top" :model="params1" ref="formItem" :rules="createRuless">
                <Row>
                    <Col span="8">
                    <FormItem label="联系结果" v-if="contactshow">
                        <RadioGroup v-model="params1.clue_status_id" @on-change="changeclue">
                            <Radio :label="item.value" v-for="item in clueList" :key="item.value"
                                   v-if="+item.value !== 9&&+item.value !== 7"><span>{{ item.label }}</span></Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="联系方式" v-if="params1.clue_status_id == 7" prop="contact_type">
                        <RadioGroup v-model="params1.contact_type">
                            <Radio :label="1"><span>微信</span></Radio>
                            <Radio :label="2"><span>电话</span></Radio>
                            <Radio :label="3"><span>其他</span></Radio>
                        </RadioGroup>
                    </FormItem>
                    <Timeline style="max-height: 380px; overflow: auto;" v-if="contact.length">
                        <TimelineItem v-for="item in contact" :key="item.id">
                            <p class="time ivu-mb-8">{{ item.created_at }}</p>
                            <p class="content ivu-mb-8">{{ item.remark }}</p>
                            <p class="consultant ivu-mb-8">
                                <span class="c-inr ivu-mr-8">{{
                                    item.realname
                                }}</span>
                                <Badge v-if="item.status_name === '未联系上'" status="success" :text="item.status_name" ></Badge>
                                <Badge v-if="item.status_name === '无效'" status="processing" :text="item.status_name" ></Badge>
                                <Badge v-if="item.status_name === '转客户'" status="warning" :text="item.status_name" ></Badge>
                                <Badge v-if="item.status_name === '新数据'" status="default" :text="item.status_name" ></Badge>
                            </p>
                        </TimelineItem>
                    </Timeline>
                    </Col>
                    <Col span="16" v-if="contactshow">
                    <template v-if="params1.clue_status_id === '8'">
                        <Row :gutter="24">
                            <Col span="5">
                            <FormItem label="姓名">
                                <Input v-model="params1.userName" placeholder="请输入姓名" ></Input>
                            </FormItem>
                            </Col>
                            <Col span="6">
                            <FormItem label="性别">
                                <RadioGroup v-model="params1.sex">
                                    <Radio :label="0">未知</Radio>
                                    <Radio :label="1">男</Radio>
                                    <Radio :label="2">女</Radio>
                                </RadioGroup>
                            </FormItem>
                            </Col>
                            <Col span="4">
                            <FormItem label="年龄" prop="age">
                                <InputNumber :max="100" :min="1" v-model="params1.age"></InputNumber>
                            </FormItem>
                            </Col>
                            <Col span="9">
                            <FormItem label="城市" required>
                                <jgcheckcity ref="checkcity" v-if="cityshow" @cityvalue="cityvalue" v-model="city_id" :name="`call`"></jgcheckcity>
                            </FormItem>
                            </Col>
                        </Row>
                        <Row :gutter="24">
                            <Col span="8">
                            <FormItem label="手机号" prop="mobile">
                                <Input v-model="params1.mobile" @on-keyup="params1.mobile=params1.mobile.replace(/\s+|[\r\n]/g,'')" @on-blur="telrepeat(params1.mobile)"
                                       placeholder="请输入手机号" ></Input>
                                <div style="color:#ff9900;font-size:18px" v-if="patientStatus">！老患者到诊</div>
                            </FormItem>
                            </Col>
                            <Col span="8">
                            <FormItem label="微信号">
                                <Input v-model="params1.weChartNum" @on-keyup="params1.weChartNum=params1.weChartNum.replace(/\s+|[\r\n]/g,'')" @on-blur="WXrepeat(params1.weChartNum)"
                                       placeholder="请输入微信号" ></Input>
                            </FormItem>
                            </Col>
                        </Row>
                        <Row :gutter="24">
                            <Col span="8">
                            <FormItem label="一级病种" prop="oneDiseases">
                                <Select placeholder="请选择一级病种" v-model="params1.oneDiseases" clearable
                                        :key="Math.random() * 10 + 1" @on-clear="clearOne" @on-change="changeOne">
                                    <Option v-for="item in diseasesArr1" :value="item.value" :key="item.value">{{
                                    item.label }}</Option>
                                </Select>
                            </FormItem>
                            </Col>
                            <Col span="8">
                            <FormItem label="二级病种" :key="Math.random() * 10 + 1" prop="twoDiseases" :rules="twoRules"
                                      v-show="diseasesArr2.length>0">
                                <Select placeholder="请选择二级病种" v-model="params1.twoDiseases" clearable>
                                    <Option v-for="item in diseasesArr2" :value="item.value" :key="item.value">{{
                                    item.label }}</Option>
                                </Select>
                            </FormItem>
                            </Col>
                            <Col span="8">
                            <FormItem label="患者状态" prop="patientStatus">
                                <Select placeholder="请选择" v-model="params1.patientStatus" clearable>
                                    <Option v-for="item in patientStatusArr" :value="item.value" :disabled="
                                        +item.is_select === 0
                                    " :key="item.value">{{ item.label }}</Option>
                                </Select>
                            </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span="12">
                            <FormItem label="部位" prop="bodyPart" :rules="bodyPartRule">
                                <TreeSelect :max-tag-count="2" v-model="params1.bodyPart" :data="postList" clearable
                                            multiple ></TreeSelect>
                            </FormItem>
                            </Col>
                        </Row>
                        <template v-if="
                            +params1.patientStatus === 2 ||
                                +params1.patientStatus === 1
                        ">
                            <FormItem label="下次回访时间" prop="day">
                                <Row :gutter="16">
                                    <Col span="6">
                                    <InputNumber :formatter="$inputday" :step="1" :min="0" v-model.number="params1.day"
                                                 @on-change="
                                                     blurday(params1.day)
                                                 ">
                                    </InputNumber>
                                    </Col>
                                    <Col span="4">天后</Col>
                                    <Col span="12">
                                    <DatePicker :editable="false" :options="optionss" type="date" v-model="DatePicker"
                                                @on-change="
                                                    changeday(DatePicker)
                                                " placeholder="请输入回访时间">
                                    </DatePicker>
                                    </Col>
                                </Row>
                            </FormItem>
                        </template>
                        <template v-if="+params1.patientStatus === 1">
                            <FormItem label="预到时间" prop="day1">
                                <Row :gutter="16">
                                    <Col span="6">
                                    <InputNumber :formatter="$inputday" :step="1" :min="0" v-model.number="params1.day1"
                                                 @on-change="
                                                     blurday1(params1.day1)
                                                 ">
                                    </InputNumber>
                                    </Col>
                                    <Col span="4">天后</Col>
                                    <Col span="12">
                                    <DatePicker :editable="false" :options="optionss" type="date" v-model="DatePicker1"
                                                @on-change="
                                                    changeday1(DatePicker1)
                                                " placeholder="请输入预到时间">
                                    </DatePicker>
                                    </Col>
                                </Row>
                            </FormItem>
                        </template>
                    </template>
                    <FormItem label="备注" prop="remark" :rules="remarkRule">
                        <Input type="textarea" placeholder="请备注原因" v-model="params1.remark"
                               :autosize="{ minRows: 2, maxRows: 8 }" ></Input>
                    </FormItem>
                    </Col>
                </Row>
            </Form>

            <div slot="footer">
                <Button @click="handleDrawerCancel('formItem')">取消</Button>
                <Button type="primary" :loading="remarksloading" @click="handlesearch('formItem')">确定</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
    // import jgcheckcity from '@/components/checkcity';
    import {
        cluecallselectinfo,
        cluecalllist,
        cluecallcontact,
        getCluecallcontact
    } from '@api/hqapi/indexone';
    import {
        patientindexsearchcity, repeatCallData,
        patientindexsearchmobile,
        repeatbaiyou
    } from '@api/hqapi';
    import {searchClue} from '@/api/globalsearch.js';
export default {
    components: {  },
    data(){
        const validateMobile = (rule, value, callback) => {
                if(value === '') {
                    callback();
                }else {
                    let reg = /^\d{10,12}$/;
                    if(reg.test(value)) {
                        callback();
                    }else {
                        callback(new Error('请输入正确的联系号码'));
                    }
                }
            };
        return{
            columns: [
                {
                    title: '来电号码',
                    // slot: 'info',
                    key: 'called_tel',
                    minWidth: 140,
                },
                {
                    title: '归属部门',
                    key: 'department_name',
                    minWidth: 100,
                    render: (h,params) => {
                        return h('span',params.row.department_name ? params.row.department_name : '/'); 
                    }
                },
                {
                    title: '设备别名',
                    key: 'device_name',
                    minWidth: 100,
                    render: (h,params) => {
                        return h('span',params.row.device_name ? params.row.device_name : '/'); 
                    }
                },
                {
                    title: '通话时长',
                    key: 'duration_str',
                    minWidth: 100,
                    render: (h,params) => {
                        return h('span',params.row.duration_str ? params.row.duration_str : '/'); 
                    }
                },
                {
                    title: '来电时间',
                    key: 'call_time',
                    minWidth: 180,
                    render: (h,params) => {
                        return h('span',params.row.call_time ? params.row.call_time : '/'); 
                    }
                },
                {
                    title: '来电状态',
                    // key: '',
                    slot: 'callState',
                    minWidth: 100,
                },
                {
                    title: '联系人员',
                    key: 'operation_name',
                    minWidth: 100,
                    render: (h,params) => {
                        return h('span',params.row.operation_name ? params.row.operation_name : '/'); 
                    }
                },
                {
                    title: '操作',
                    slot: 'option',
                    minWidth: 100,
                },
            ],
            optionss: {
                    disabledDate(date) {
                        return (
                            date && date.valueOf() < Date.now() - 24 * 3600 * 1000
                        );
                    }
            },
            contactClue: false,
            loading: false,
            callData: [],
            createData: {
                gender: '',
                age: 0,
                wechat_id: '',
                parts_name: '',
                city_name: '',
                mobile: '',
                customer_remark: '',
                is_add: false
            },
            params1: {
                id: undefined,
                clue_status_id: '8',
                remark: '',
                day: 1,
                bodyPart: [],
                weChartNum: '',
                mobile: '',
                day1: 0,
                userName: '',
                contact_type: '',
                age: null,
                birthday: '',
                sex: '',
                city_id: '',
                oneDiseases: '',
                twoDiseases: '',
                patientStatus: '2'
            },
            contactshow: true,
            data: [],
            createRuless: {
                contact_type: [
                    {
                        required: true,
                        message: '请选中联系方式'
                    }
                ],
                remark: [
                    {
                        required: true,
                        type: 'string',
                        message: '请输入备注原因',
                        trigger: 'blur'
                    }
                ],
                mobile: [{ validator: validateMobile, trigger: 'blur' }],

                city: [
                    {
                        required: true,
                        message: '请选择城市',
                        trigger: 'change'
                    }
                ],
                age: [
                    {
                        required: true,
                        message: '请填写年龄',
                        type: 'number',
                        trigger: 'blur,change'
                    }
                ],
                oneDiseases: [
                    {
                        required: true,
                        message: '请选择一级病种',
                        trigger: 'change'
                    }
                ],
                twoDiseases: [
                    {
                        required: true,
                        message: '请选择二级病种',
                        trigger: 'change'
                    }
                ],
                patientStatus: [
                    {
                        required: true,
                        message: '请选择患者状态',
                        trigger: 'change'
                    }
                ],
                day: [
                    {
                        required: true,
                        type: 'number',
                        message: '请输入回访时间',
                        trigger: 'blur'
                    }
                ],
                day1: [
                    {
                        required: true,
                        type: 'number',
                        message: '请输入预约',
                        trigger: 'blur'
                    }
                ]
            },
            clueList: [],
            contact: [],
            city_id: [],
            cityshow: true,
            patientStatus: false,// 是否老患者到诊状态
            diseasesArr1: [],
            diseasesArr2: [],
            patientStatusArr: [],
            postList: [],
            DatePicker: new Date(new Date().getTime() + 86400000),
            DatePicker1: new Date(new Date().getTime()),
            remarksloading: false,
            total:0,
            pageOpts: [10, 15, 20, 30, 50],
            params:{
                page: 1,
                pageSize: 10,
            },
            keyword:''
        };
    },
    computed: {
        bodyPartRule() {
            if(this.params1.oneDiseases === '1') {
                return {
                    required: true,
                    validator: (rule, value, callback) => {
                        if(value.length) {
                            callback();
                        }else {
                            callback(new Error('请选择部位'));
                        }
                    },
                    trigger: 'change'
                };
            }else {
                return {
                    required: false,
                    type: 'array',
                    trigger: 'change'
                };
            }
        },
        remarkRule() {
            if(this.params1.clue_status_id === '8') {
                return {
                    required: false,
                    type: 'string',
                    message: '请输入备注原因',
                    trigger: 'blur'
                };
            }else {
                return {
                    required: true,
                    type: 'string',
                    message: '请输入备注原因',
                    trigger: 'blur'
                };
            }
        },
        twoRules() {
            if(this.diseasesArr2.length) {
                return {
                    required: true,
                    message: '请选择二级病种',
                    trigger: 'change'
                };
            }else {
                return {
                    required: false,
                    message: '请选择二级病种',
                    trigger: 'change'
                };
            }
        },
        birthdays() {
            if(this.params1.age !== '') {
                var year = new Date().getFullYear() - this.params1.age;
                return year + '-01' + '-01';
            }
        }
        },
    methods: {
        initial(val){
            cluecallselectinfo().then(res => {
                this.clueList = res.clue_status;
            });
            if(val == ''){
                this.callData = [];
            }else{
                this.keyword=val
                this.getsearchClue(val);
            }
          
        },
        /* @函数功能: 分页 */
        changepage(e) {
            this.params.page = e;
            this.getsearchClue(this.keyword);
        },
        /* @函数功能: 每页数量 */
        changepageSize(e) {
            this.params.pageSize = e;
            this.getsearchClue(this.keyword);
        },
        getsearchClue(val){
            this.loading=true
            searchClue({type: 'call',true_keyword: val,...this.params}).then(res => {
                this.total = res.total;
                this.callData = res.list;
                this.loading=false
            }).catch(()=>{
                this.loading=false
            });
        },
        cityvalue(city) {
                this.city_id = city;
                this.params1.city_id = city.join(',');
        },
        changeclue(e) {
            for(let item of this.clueList) {
                if(e === item.value) {
                    if(+item.value === 8) this.contactDatas = true;
                    else this.contactDatas = false;
                }
            }
        },
        clearOne() {
                this.diseasesArr2 = [];
                this.params1.twoDiseases = '';
        },
        changeOne(value) {
            if(value) {
                this.diseasesArr2 = this.diseasesArr1.filter(
                    ee => {
                        return ee.value == value; 
                    }
                )[0].children;
                this.params1.twoDiseases = '';
                if(!this.diseasesArr2.length) {
                    this.$nextTick(() => {
                        this.$refs.formItem.validateField('twoDiseases');
                    });
                }
            }
        },
        telrepeat(data) {
            let config = {
                id: this.params1.id === undefined ? 0 : this.params1.id,
                mobile: data
            };
            patientindexsearchmobile(config).then(res => {
                if(+res.result === 1) {
                    this.$Message.error({
                        duration: 2.5,
                        content: '该手机号码已存在'
                    }
                    );
                }
            });
            repeatbaiyou({mobile: data}).then(res => {
                // console.log(res,'res')
                this.patientStatus = res;
            });
            },
        // 联系线索客户
        handleContactClue(row) {
                if(+row.clue_status_id !== 8) this.contactshow = true;
                else this.contactshow = false;
                this.$refs.formItem.resetFields();
                this.cityshow = false,
                getCluecallcontact({ id: row.id }).then(res => {
                    if(
                        res.default_city &&
                        JSON.stringify(res.default_city) !== '{}'
                    ) {
                        this.optionscity = [
                            {
                                value: res.default_city.city_id,
                                label: res.default_city.city_name
                            }
                        ];
                        // this.params1.city = res.default_city.city_id;
                        this.params1.city_id = [];
                        this.cityshow = true;
                    }
                    this.createData = {
                        gender: res.info.gender,
                        age: res.info.age,
                        wechat_id: res.info.wechat_id,
                        parts_name: res.info.parts_name,
                        city_name: res.info.city_name,
                        mobile: res.info.mobile,
                        customer_remark: res.info.customer_remark,
                        is_add: res.info.is_add
                    },
                    this.logs(row.info);
                    this.contact = res.contact;
                    this.postList = res.body_parts_list;
                    this.diseasesArr1 = res.diseases;
                    this.patientStatusArr = res.patient_status;
                });
                this.contactClue = true;
                this.params1.id = row.id;
                this.params1.mobile = row.called_tel;
                this.params1.patientStatus = '2';
                this.params1.city = [];
        },
        // 搜索手机号
        handlesearch(name) {
            this.$refs[name].validate(valid => {
                if(valid) {
                    if(this.params1.clue_status_id === '8') {
                        let config = {
                            id: this.params1.id === undefined ? 0 : this.params1.id,
                            mobile: this.params1.mobile,
                            wechat_id: this.params1.weChartNum
                        };
                        patientindexsearchmobile(config).then(res => {
                            if(+res.result === 1) {
                                this.$Modal.confirm({
                                    title: '提示',
                                    content: '<p>该手机号码已存在，是否继续录入?</p>',
                                    onOk: () => {
                                        this.handleSubmit();
                                    },
                                    onCancel: () => {
                                        this.remarksloading = false;
                                    }
                                });
                            }else if(+res.result === 2) {
                                this.$Modal.confirm({
                                    title: '提示',
                                    content: '<p>该微信号已存在，是否继续录入?</p>',
                                    onOk: () => {
                                        this.handleSubmit();
                                    },
                                    onCancel: () => {
                                        this.remarksloading = false;
                                    }
                                });
                            }else if(+res.result === 3) {
                                this.$Modal.confirm({
                                    title: '提示',
                                    content: '<p>该手机号/微信号已存在，是否继续录入?</p>',
                                    onOk: () => {
                                        this.handleSubmit();
                                    },
                                    onCancel: () => {
                                        this.remarksloading = false;
                                    }
                                });
                            }else {
                                this.handleSubmit();
                            }
                        });
                    }else {
                        this.handleSubmit();
                    }
                }
            });
        },
        handleSubmit(name) {
            let params = {
                id: this.params1.id,
                clue_status_id: this.params1.clue_status_id,
                remark:
                    this.params1.clue_status_id === '8'
                        ? ''
                        : this.params1.remark,
                day:
                    this.params1.clue_status_id === '8' &&
                    (this.params1.patientStatus === '2' ||
                    this.params1.patientStatus === '1')
                        ? parseInt(
                            new Date(this.DatePicker).getTime() / 1000
                        )
                        : '',
                type: 3,
                patient_status_id:
                    this.params1.clue_status_id === '8'
                        ? this.params1.patientStatus
                        : '',
                user_name:
                    this.params1.clue_status_id === '8'
                        ? this.params1.userName
                        : '',
                age:
                    this.params1.clue_status_id === '8'
                        ? this.params1.age
                        : '',
                birthday:
                    this.params1.clue_status_id === '8'
                        ? this.birthdays
                        : '',
                patient_diseases_id:
                    this.params1.clue_status_id === '8'
                        ? this.params1.oneDiseases
                        : '',
                patient_diseases_child_id:
                    this.params1.clue_status_id === '8'
                        ? this.params1.twoDiseases
                        : '',
                patient_remake:
                    this.params1.clue_status_id === '8'
                        ? this.params1.remark
                        : '',
                city_id: this.params1.clue_status_id === '8' ? this.params1.city_id : '',
                appointment_day:
                    this.params1.clue_status_id === '8' &&
                    this.params1.patientStatus === '1'
                        ? parseInt(
                            new Date(this.DatePicker1).getTime() /
                                1000
                        )
                        : '',
                gender:
                    this.params1.clue_status_id === '8'
                        ? this.params1.sex
                        : '',
                // city_name: this.params1.city
                //     ? this.optionscity.filter(
                //         (ee) => ee.value === this.params1.city
                //     )[0].label
                //     : "",
                wechat_id:
                    this.params1.clue_status_id === '8'
                        ? this.params1.weChartNum
                        : '',
                mobile:
                    this.params1.clue_status_id === '8'
                        ? this.params1.mobile
                        : '',
                body_parts_id: this.params1.clue_status_id === '8'
                    ? this.params1.bodyPart.join(',')
                    : '',
                contact_type: this.params1.clue_status_id == 7 ? this.params1.contact_type : ''
            };
            this.remarksloading = true;
            cluecallcontact(params)
                .then(() => {
                    this.city_id = [];
                    this.remarksloading = false;
                    this.askData();
                    this.$Message.success('联系成功!');
                    this.contactClue = false;
                    this.diseasesArr2 = [];
                    this.params1 = {
                        id: undefined,
                        clue_status_id: '8',
                        remark: '',
                        day: 1,
                        day1: 0,
                        bodyPart: [],
                        userName: '',
                        weChartNum: '',
                        mobile: '',
                        age: null,
                        birthday: '',
                        sex: '',
                        city_id: '',
                        oneDiseases: '',
                        twoDiseases: '',
                        patientStatus: '2'
                    };
                    this.$refs.formItem.resetFields();
                })
                .catch(() => {
                    this.remarksloading = false;
            });
        },
        handleDrawerCancel(name) {
                this.city_id = [];
                this.$refs[name].resetFields();
                this.contactClue = false;
                this.params1 = {
                    id: undefined,
                    clue_status_id: '8',
                    remark: '',
                    day: 1,
                    day1: 0,
                    userName: '',
                    weChartNum: '',
                    mobile: '',
                    contact_type: '',
                    age: null,
                    birthday: '',
                    sex: '',
                    city_id: '',
                    oneDiseases: '',
                    twoDiseases: '',
                    patientStatus: '2'
                };
                this.diseasesArr2 = [];
                this.diseasesArr1 = [];
                this.patientStatus = false;
            },
    }
    
};
</script>